package org.mp3weezel.strands.services;

import java.io.InputStream;
import java.util.Map;

import org.mp3weezel.strands.StrandsAPI;
import org.mp3weezel.strands.StrandsServiceException;

public abstract class AbstractService {

	protected StrandsAPI api;

	public AbstractService(StrandsAPI api) {
		this.api = api;
	}

	protected Object request(String uri, Map<String, String[]> parameters)
			throws StrandsServiceException {
		if (api.getRequestCache() != null) {
			Object cacheHit = api.getRequestCache().queryCache(uri, parameters);
			if (cacheHit != null) {
				return cacheHit;
			}
		}
		return api.getStrandsService().request(uri, parameters);
	}

	protected int requestHttp(String uri, Map<String, String[]> parameters) throws StrandsServiceException {
		return api.getStrandsService().requestHttp(uri, parameters);
	}
	
	protected InputStream requestFile(String uri, Map<String, String[]> parameters) throws StrandsServiceException {
		return api.getStrandsService().requestFile(uri, parameters);
	}
	
	
	protected void assertNotNegative(String fieldName, int value) {
		if (value < 0) {
			throw new IllegalArgumentException(fieldName
					+ " must be positive but is " + value);
		}
	}

	protected void assertNotEmpty(String fieldName, String value) {
		if (value == null || value.isEmpty()) {
			throw new IllegalArgumentException(fieldName
					+ " must be set but is " + value);
		}
	}

	protected void assertNotEmpty(String fieldName, String[] value) {
		if (value == null || value.length == 0) {
			throw new IllegalArgumentException(fieldName
					+ " must be set but is " + value);
		}
		for (String string : value) {
			if (string != null && string.length() > 0) {
				// valid
				return;
			}
		}
		throw new IllegalArgumentException(fieldName + " must be set but is "
				+ value);
	}

}
